


const VERSION = "v1.0.0";
const CACHE_FILES = [
    /\/static\/[\w\W]+(\.\w+)$/
];
// self.addEventListener('install', function (event) {
//     // var cacheOpenPromise = caches.open(VERSION).then(function (cache) {
//     //     return cache.addAll(CACHE_FILES);
//     // });
//     // event.waitUntil(cacheOpenPromise);
//     event.waitUntil(self.skipWaiting());
// });

//当安装成功后，serviceworker就会激活，这时就会处理 activate 事件回调
//每次加载页面都执行
self.addEventListener('activate', function (event) {
    event.waitUntil(Promise.all([cleanCaches(), self.clients.claim()]));
});


self.addEventListener('fetch', function (event) {
    // 判断当前请求是否需要缓存
    var needCache = CACHE_FILES.some(function (url) {
        return event.request.url.match(url);
    });
    if (needCache) {
        event.respondWith(
            caches.match(event.request).then(function (cache) {
                if (cache) return cache;
                return fetchCache(event);
            }).catch(function (err) {
                // console.log('fetch', err);
                return fetchCache(event);
            })
        );
    }
})

self.addEventListener('notificationclick', function (e) {
    const action = e.action;
    e.notification.close();
    const handleClean = function () {
        if (action === 'update') {
            return cleanCaches(true)
        }
    }
    e.waitUntil(
        Promise.all([handleClean(), self.clients.matchAll()]).then(function (results) {
            // 获取所有clients
            const clients = results[1];
            if (!clients || clients.length === 0) {
                // self.clients.openWindow && self.clients.openWindow('http://127.0.0.1');
                return;
            }
            clients[0].focus && clients[0].focus();
            clients.forEach(function (client) {
                // 使用postMessage进行通信
                client.postMessage(action);
            });
            // self.clients.claim()，//claim() 方法允许一个激活的 service worker 将自己设置为其 scope 内所有clients 的controller
        })
    );
})
/**
 * 缓存所需数据
 * @param {*} event 
 */
function fetchCache(event) {
    var requestToCache = event.request.clone();
    return fetch(requestToCache).then(function (response) {
        if (!response || response.status !== 200) {
            return response;
        }
        var responseToCache = response.clone();
        caches.open(VERSION).then(function (cache) {
            cache.put(requestToCache, responseToCache);
        })
        return response;
    });
}

/**
 * 清除所有缓存
 * @param {*}
 */
function cleanCaches(isAll) {
    // 清理旧版本
    return caches.keys().then(function (cacheList) {
        return Promise.all(
            cacheList.map(function (cacheName) {
                // console.log("cacheName", cacheName)
                if (isAll) return caches.delete(cacheName);
                if (cacheName !== VERSION) return caches.delete(cacheName);
            })
        );
    }).catch(function () {
        return
    })
}